import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-10-25
 * Time: 2:54
 */
public class Demo4 {
    public static void main(String[] args) throws SQLException {
        //1. 建立数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java1025?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //2. 与数据库建立连接
        Connection connection = dataSource.getConnection();

        //3. 构造sql
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);

        //4. 将sql发送给数据库执行
        ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()) {
            System.out.print("id = " + resultSet.getInt("id"));
            System.out.print(" ");
            System.out.println("name = " + resultSet.getString("name"));
        }

        //5. 释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
